package com.express.core.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.express.conf.WechatConfig;
import com.express.entity.User;
import com.express.entity.UserOrders;
import com.express.entity.WxUser;
import com.express.service.IWxUserService;
import com.express.sys.service.UserService;
import com.express.util.HttpUtils;
import com.express.util.PropertyUtils;
import com.express.util.ToolUtils;
import com.express.util.wx.WeixinUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.*;

/**
 * 微信请求处理控制类
 * @author lingzhouf
 */
@Controller
public class WechatController {

    private static Logger log = LoggerFactory.getLogger(WechatController.class);

    @Autowired
    IWxUserService wxUserService;
    @Autowired
    UserService userService;
    /**
     * 获取用户微信code
     * @return
     */
    @RequestMapping(value="/getCode",method= RequestMethod.GET)
    public String  getUserCode (HttpServletRequest request, ModelMap map,String type) {
        StringBuffer url = null;
        try {
            /*你的授权回调地址*/
            String redirect_uri= URLEncoder.encode(PropertyUtils.getString("pro.req.path")+"getOpenId", "UTF-8");
            //简单获取openid的话参数response_type与scope与state参数固定写死即可
//          String weixin = PropertyUtils.getString("pro.req.path")+"get-weixin-code.html";
            String weixin = WechatConfig.AUTHORIZE_OAUTH_URL;
            url = new StringBuffer(weixin+"?appid="+WechatConfig.APP_ID+"&redirect_uri="+redirect_uri+
                    "&response_type=code&scope=snsapi_userinfo&state=wechat_lbt"+type);
            log.info("获取微信code...");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:"+url.toString();
    }

    /**根据 code 获取微信的OpenId */
    @RequestMapping("/getOpenId")
    public ModelAndView getOpenId(@RequestParam("code") String code,@RequestParam("state") String state, HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();//实例化一个View的ModelAndView对象
        log.info("-------------进入了getOpenId方法！！--------------------------");
        String apiUrl = WechatConfig.GET_OAUTH_TOKEN_URL;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appid", WechatConfig.APP_ID);
        map.put("secret", WechatConfig.APP_SECRET);
        map.put("code", code);
        map.put("grant_type", "authorization_code");
        // 拼接微信获取OpenId的url
        String url = ToolUtils.getUrl(apiUrl, map);
        // 要跳转的页面
        String reurl = "my";
        log.info("-----------拼接后的获取OpenId的URL为：" + url);
        String res = HttpUtils.httpGet(url, new LinkedHashMap<String, String>(), "UTF-8");
        JSONObject ret = JSON.parseObject(res);
        if (log.isInfoEnabled()) {
            log.info("获取openId返回信息：" + ret);
        }
        if (ret.get("openid") != null && StringUtils.hasText((String) ret.get("openid"))) {
            WechatConfig.WEIXIN_OPENID = ret.get("openid")+"";
            request.getSession().setAttribute(WechatConfig.SESSION_OPENID, ret.get("openid"));
            if (log.isInfoEnabled()) {
                log.info("openid是：" + ret.get("openid"));
            }
            WxUser user = syncUser(request,ret.getString("refresh_token"), ret.getString("access_token"), WechatConfig.WEIXIN_OPENID);
            if(user!=null){
                modelAndView.addObject("user",user);
            }
            boolean isbind = false;
            // 判断是否绑定手机号
            if(user!=null ){
                isbind = StringUtils.isEmpty(user.getPhone())?false:true;
            }
            if(!isbind){
                reurl = "verification";
            }
            // 根据sate判断是否要跳转的页面
            if(!StringUtils.isEmpty(state)){
                if(state.contains("send")){
                    reurl = isbind?"send":"verification";
                } else if(state.contains("query")){
                    reurl = isbind?"examine":"verification";
                }
            }
            // 查询是否有权查询路由信息
            if(isbind){
                log.info("用户：{},手机号：{},查询是否有权查询路由信息",user.getId(),user.getPhone());
                User userBack = new User();
                userBack.setPhone(user.getPhone());
                userBack = userService.getUser(userBack);
                if(userBack!=null){
                    log.info("绑定后台用户是：{},有权限查询跟录入信息",userBack.getId());
                    request.getSession().setAttribute("sysUserId",userBack.getId());
//                    modelAndView.addObject("sysUserId",userBack.getId());
                }
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info("获取openId失败！");
            }
            modelAndView.setViewName("error");
            return modelAndView;
        }
        modelAndView.setViewName(reurl);
        modelAndView.addObject("order", new UserOrders());
        return modelAndView;
    }

    /**
     * 同步用户信息
     */
    private WxUser syncUser(HttpServletRequest request,String refreshToken,String accessToken,String openid){
        WxUser user = null;
        // 查询是否存在
        Map<String,Object> map = new HashMap<>();
        map.put("openId",openid);
        List<WxUser> list = wxUserService.query(map);
        if(list==null || list.size()==0){
            // 从微信端获取
            user = WeixinUtil.getUserInfo(accessToken, openid);
            if(user!=null){
                user.setCreateDate(new Date());
                // 保存用户信息
                user.setStatus(1);
                wxUserService.save(user);
                request.getSession().setAttribute("userId",user.getId());
            } else {
                // 刷新
                String ret = WeixinUtil.refreshAuthToken(refreshToken, openid);
                accessToken = JSON.parseObject(ret).getString("access_token");
                user = WeixinUtil.getUserInfo(accessToken, openid);
                user.setCreateDate(new Date());
                // 保存用户信息
                wxUserService.save(user);
                request.getSession().setAttribute("userId", user.getId());
            }
        } else {
            user = list.get(0);
            request.getSession().setAttribute("userId",user.getId());
        }
        return user;
    }
}
